package com.ceiec.base.event;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.stereotype.Component;

import java.util.LinkedHashSet;
import java.util.Set;

/**
 * desc:
 * 参考spring
 * {@link SimpleApplicationEventMulticaster}
 *
 * @author : ckl
 * creat_date: 2019/11/16 0016
 * creat_time: 10:40
 **/
@Slf4j
@Component
public class CommonApplicationEventMulticaster implements ICommonApplicationEventMulticaster {
    public final Set<ICommonApplicationEventListener<?>> applicationListeners = new LinkedHashSet<>();

    @Override
    public void addApplicationListener(ICommonApplicationEventListener<?> listener) {
        applicationListeners.add(listener);
    }

    @Override
    public void removeApplicationListener(ICommonApplicationEventListener<?> listener) {
        applicationListeners.remove(listener);
    }

    @Override
    public void removeAllListeners() {
        applicationListeners.clear();
    }

    @Override
    @SuppressWarnings({"rawtypes", "unchecked"})
    public void multicastEvent(CommonApplicationEvent event) {
        try {
            for (ICommonApplicationEventListener applicationListener : applicationListeners) {
                if (applicationListener.supportsEventType(event)) {
                    applicationListener.onApplicationEvent(event);
                }
            }
        } catch (Exception e) {
            log.error("{}",e);
        }
    }
}
